package down{
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.StatusEvent;
	import flash.external.ExternalInterface;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	import flash.utils.Endian;
	import flash.utils.getTimer;
	import ui.down.DownloadingUI;
	import utils.PNGEncoder;
	/**
	 * suxiaolei suxiaolei123
	 * 直接输入su     
	 * 然后输入密码 tomgw163.com
		cd /www/test.xbsafe.cn/webspeed
		cd flash
		ls 显示文件列表
		rz -y上传就这个路径下就可以了。
		sz web.swf 下载SWF
		http://220.181.85.226/webspeed/main.html
			http://www.cnblogs.com/meteoric_cry/archive/2011/06/18/2084371.html
				
		下载测速最后的显示规则
		舞台尺寸
	 * @author 
	 */
	public class Downing extends DownloadingUI{
		
		private static var _instance:Downing;
		public static function get instance():Downing{
			if(_instance) return _instance;
			return _instance=new Downing();
		}
		
		private const TIME:int=15;
		private const DOWN:int=1;
		private const UNLOAD:int=2;
		
		/**当前正在下载的进程*/
		private var downloads:Array=[];
		/**请求回来的用户宽带信息*/
		private var bandInfo:Object;
		/**要回传的URLInfo*/
		private var urlInfo:String = "";
		/**统计四个下载的数据*/
		private var loades:Array;
		/**统计四个上传的数据*/
		private var unLoaders:Array;
		/**时间计数器*/
		private var timerCount:int;
		/**当前的测试状态*/
		private var status:int;
		/**统计当前的总进度值*/
		private var total:int;
		/**当前的下载数据*/
		private var timeData:Object;
		private var date:Date;
		
		public function start():void{
			this.loades=[[], [], [], []];
			this.unLoaders=[];
			this.timeData={};
			this.status=this.DOWN;
			this.addEventListener(Event.ADDED_TO_STAGE,this.onAddedToStage);
			App.scene.scene=this;
			this.tfTitle.text="系统将根据15秒内的下载速率计算出您的平均网速。";
		}
		
		/**开始下载测速*/
		private function startDownLoad():void{
			for(var i:int=0;i<4;i++){
				//if(!this.downloads[i]) this.downloads[i]=new Download("http://220.181.85.226:80/webspeed/flash/speed.dat");
				if(!this.downloads[i]) this.downloads[i]=new Download(bandInfo["testaddr"]);
				this.downloads[i].start();
			}
			this.timerCount=0;
			this.timeData.loadStart=this.getFullTime();
			App.timer.doLoop(1000,this.doTime);
		}
		//解析url地址数据
		
		private function getUrl():void{  
			if(!ExternalInterface.available) return;
            var str:String = ExternalInterface.call("function getUrl(){return document.location.href;}");
            if (!str) return;
			
			str = str.substr(str.indexOf("?"), str.length);
			str = unescape(str);
			str = str.substr(6, str.length);
			this.urlInfo = str;
			this.bandInfo=Tools.strTOobj(str, ",", "=");
			this.bandInfo["server"] = Tools.strTOobj(this.bandInfo["server"], "#", "*");
			this.startDownLoad();
        }
		/**添加到舞台以后调用*/
		private function onAddedToStage(evt:Event):void{
			this.getUrl();
			//this.startDownLoad();
			//this.startUnLoad();
			//App.timer.doLoop(1000,this.doTime);
			//trace("start");
			
		}
		/**测速过程中计算进度*/
		private function doTime():void{
			if(this.status==this.DOWN){
				var download:Download;
				total=0
				var len:int = this.downloads.length;
				for (var i:int = 0; i < len; i++) {
					download=this.downloads[i];
					download.firstLoaded =download.bytesLoaded - download.firstTotal;
					this.loades[i].push(download.firstLoaded);
					total += download.firstLoaded;
					download.firstTotal += download.bytesLoaded-download.firstTotal;
				}
				total = total /1024;
				this.tfSpeed.text="即时下载速度："+String(int(total*10) / 10) +"KB /秒";
			}else{
				this.unLoaders.push(this.total);
				this.tfSpeed.text="即时上传速度："+Math.round(total/1024)+"KB /秒";
				total=0;
			}
			
			this.timerCount++;
			this.mcProgress.value= this.timerCount/this.TIME;//进度条
			if (this.timerCount >= this.TIME) {
				if(this.status==this.DOWN){
					this.timeData.loadEnd=this.getFullTime();
					this.timeData.unLoadStart=this.getFullTime();
					this.startUnLoad();
				}else{
					App.timer.clearTimer(this.doTime);
					this.timeData.unLoadEnd=this.getFullTime();
					this.timeData.urlInfo=this.urlInfo;
					DownResult.instance.start(this.loades,this.unLoaders,this.bandInfo,this.timeData);
				}
			}
		}
		/**Socket连接地址*/
		private var port:int=21356;
		/**Socket连接地址*/
		private var host:String="220.181.85.226";
		/**上传测试用的Socket*/
		private var socket:Socket;
		/**上传的计时器*/
		private var timer:int;
		/**上传测试用的二进制数组*/
		private var sendByte:ByteArray;
		
		/**开始上传测试*/
		private function startUnLoad():void{
			this.status=this.UNLOAD;
			this.tfTitle.text="系统将根据15秒内的上传速率计算出您的平均网速。";
			this.timerCount=0;
			if(!this.socket){
				this.socket = new Socket();
				this.socket.endian=Endian.LITTLE_ENDIAN;
				this.socket.addEventListener(Event.CLOSE,this.onClose);
				this.socket.addEventListener(Event.CONNECT,this.onConnect);
				this.socket.addEventListener(StatusEvent.STATUS,this.onClose);
				this.socket.addEventListener(IOErrorEvent.IO_ERROR,this.onClose);
				this.socket.addEventListener(ProgressEvent.SOCKET_DATA,this.onProgress);
				this.socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,this.onClose);
			}
			this.socket.connect(this.host,this.port);
		}
		/**收到服务器回包后响应*/
		private function onProgress(evt:Event):void{
			if(this.socket.bytesAvailable < 4) return;
			if(this.timerCount >= this.TIME){
				this.socket.close();
				return;
			}
			
			var length:int = this.socket.readUnsignedInt();
			this.total+=length;
			//trace(length+"   "+(getTimer()-this.timer));
			//length=length/1024/((getTimer()-this.timer)/1000)
			//this.tfSpeed.text="即时上传速度："+length+"KB /秒";
			
			this.timer=getTimer();
			this.socket.writeBytes(this.sendByte);
			this.socket.flush();	
		}
		/**断开后响应*/
		private function onClose(evt:Event):void{
			
		}
		/**连接成功后调用*/
		private function onConnect(evt:Event):void{
			trace("onConnect");
			var bmd:BitmapData=App.asset.getBitmapData("png.down.button_reTest");
			var bigBmd:BitmapData=new BitmapData(60,80);
			bigBmd.copyPixels(bmd,new Rectangle(0,0,60,80),new Point(0,0));
			this.sendByte=PNGEncoder.encode(bigBmd);
			this.timer=getTimer();
			this.sendFrist();
			//this.isClose=false;
		}
		/**发送第一个包*/
		private function sendFrist():void{
			socket.writeUTFBytes("XBWEBNETSPEEDCHECK");
			socket.flush();	
		}
		private function getFullTime():String{
			this.date=new Date();
			var month:String=String("0"+(date.getMonth()+1))
			if(month.length>2) month=month.substr(1);
			var day:String=String("0"+date.getDate())
			if(day.length>2) day=day.substr(1);
			var hours:String=String("0"+date.getHours());
			if(hours.length>2) hours=hours.substr(1);
			var min:String=String("0"+date.getMinutes());
			if(min.length>2) min=min.substr(1);
			var second:String=String("0"+date.getSeconds());
			if(second.length>2) second=second.substr(1);
			
			return ""+date.getFullYear()+""+month+""+day+""+hours+""+min+""+second;
		}
	}

}